import API from '../api/index.js'
import store from '../store'

export const BASE_URL = process.env.VUE_APP_API;

export function transformUrl(url, config) {
    if(!API[url]){
        console.error(url + '：接口不存在')
    }
    
    // 从api列表中获取真实的url
    let reallyUrl = findUrl(url, config.params);
    // let reallyUrl = API[url].indexOf('uid') != -1 ? API[url].replace('[uid]', store.getters.uid) : API[url];
    // 如果有rest参数自动替换
    if(reallyUrl.indexOf('{') != -1) {
        if(config.data) {
            url = replaceUrl(reallyUrl, config.data);
        } else {
            url = replaceUrl(reallyUrl, config.params);
        }
    } else {
        url = reallyUrl
    }
    
    url = BASE_URL + url;
    if(config.params) {
        url = buildURL(url, config.params);
    }
    
    return url;
}

function findUrl(key, params) {
    let url = API[key];
    if(url.indexOf('uid') != -1) {
        url = url.replace('[uid]', params && params.uid || store.getters.uid)
    }
    return url;
}

function buildURL(url, params) {
    if(!params || !Object.keys(params).length) {
        return url
    }
    const sdata = [];
    for (let key in params) {
        let val = params[key]
        if(val !== '') {
            sdata.push(`${key}=${encode(val)}`);
        }
    }
    return `${url}?${sdata.join('&')}`;
}

function encode(val) {
    return encodeURIComponent(val)
        .replace(/%40/g, '@')
        .replace(/%3A/ig, ':')
        .replace(/%24/g, '$')
        .replace(/%2C/ig, ',')
        .replace(/%20/g, '+')
        .replace(/%5B/ig, '[')
        .replace(/%5D/ig, ']')
}

/**
 * url特殊变量替换
 * @param {string} url -要请求的url
 * @param {object} params -需要替换进url的值
 */
function replaceUrl(url, params) {
    let paramsArr = url.split('/');
    paramsArr = paramsArr.map(item => {
        if(item.indexOf('{') != -1) {
            item = item.slice(1, item.length -1);
            if(typeof params[item] == 'undefined' || params[item] === null) {
                console.warn(`${item}没有传值`)
            } else {
                let val = params[item];
                delete params[item];
                return val;
            }
        }
        return item;
    })
    return paramsArr.join('/')
}